﻿package com.bigstar.lolkor;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class Lolkor extends Activity implements OnClickListener{
    public static int[] rota_index = new int[10];
    /** Called when the activity is first created. */
    public ArrayList<SaleInfo> sale_skin = new ArrayList<SaleInfo>();
    public ArrayList<SaleInfo> sale_champ = new ArrayList<SaleInfo>();
	private ProgressDialog pd;
    @Override
    protected void onResume() {
    	ChampionData.load(this);
        super.onResume();
    }

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
        for(int i = 0; i < rota_index.length; i++){
        	rota_index[i] = -1; //rota 로테이션
        }

        ChampionData.load(this);
        setContentView(R.layout.main);
        AdView adview = (AdView)findViewById(R.id.adView);
        AdRequest re = new AdRequest(); 
        adview.loadAd(re);
        Button button = (Button)findViewById(R.id.champion_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.item_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.mastery_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.spells_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.server_status);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.builder);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.jugle_timer);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.option);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.abbreviation);
        button.setOnClickListener(this);   
        button = (Button)findViewById(R.id.sale_info);
        button.setOnClickListener(this);   
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); //공용자원
		boolean notice = pref.getBoolean("notice", false);
		String notice_name = "리그 오브 레전드 v1.0.0.151";
        if(!notice){
        	String anno = null;
            try {
    			anno = loadUpdate();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		HistoryDialog hd = new HistoryDialog(this, notice_name, anno); //FIXME 업데이트날때 저기 맨뒷숫자 바꺼줘야함
    		hd.show();	
        }else{
        	Date today = new Date();
            SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");       
    		int notice_date = pref.getInt("notice_date", 0);
    		int today_date = Integer.parseInt(formater.format(today));
    		if(today_date > notice_date){
    			SharedPreferences.Editor editor = pref.edit();
    			editor.putInt("notice_date", today_date);
    			editor.commit();
            	String anno = null;
                try {
        			anno = loadUpdate();
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		HistoryDialog hd = new HistoryDialog(this, notice_name, anno);
        		hd.show();
    		}
        }
		Thread t = new Thread(mUpdateResults);
		t.start();
    }
    
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			if(Utils.isNetwork(Lolkor.this)){
				process("http://www.leagueoflegends.co.kr");	
	            new Thread(new Runnable() {
	                @Override
	                public void run() {    
	                    runOnUiThread(new Runnable(){
	                        @Override
	                         public void run() {
	                        	update();
	                        	boolean rota_error = false;
	                    		for(int j = 0; j < rota_index.length; j++){
	                    			if(rota_index[j] == -1){
	                    				rota_error = true;
	                    			}
	                    		}
	                    		if(rota_error){
	                        		TextView tv = (TextView)findViewById(R.id.tv_system_check);
	                        		tv.setVisibility(View.VISIBLE);	
	                    		}
	                         }
	                    });
	                }
	            }).start(); 
			}else{
        		TextView tv = (TextView)findViewById(R.id.tv_system_check);
        		tv.setVisibility(View.VISIBLE);	
			}
		}

	};
	
    public void update(){
    	for(int i = 0; i < 10; i++){
    		ImageView iv = (ImageView)findViewById(R.id.rotation_00+(i*2));
    		TextView tv = (TextView)findViewById(R.id.tv_ro_00+(i*2));
    		for(int j = 0; j < ChampionData.champions.size(); j++){
    			if(ChampionData.champions.get(j).champ_id == rota_index[i]){
    				String path = "champ_img/"+ChampionData.champions.get(j).name_en+".jpg";
    				try {
    					iv.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				iv.setTag((int)j);
    				iv.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
							boolean menual = pref.getBoolean("menual", true);
    		    			if(menual){
    			    			MenualSelectDialog dialog = new MenualSelectDialog(Lolkor.this, (Integer)v.getTag());
    			    			dialog.show();
    		    			}else{
    		    	    		Intent intent = new Intent(Lolkor.this, Champion.class);
    		    				intent.putExtra("champid", ""+(Integer)v.getTag());
    		    				startActivity(intent);
    		    			}
						}
    					
    				});
    				tv.setText(ChampionData.champions.get(j).name_kor);
    				break;
    			}
    		}
    	}
    }
	public void process(String url){
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost get = new HttpPost();
			get.setURI(new URI("http://ghdnjs9012.com/Rotation.php"));

			List<NameValuePair> params = new ArrayList<NameValuePair>();

			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			get.setEntity(entity);

			HttpResponse resp = client.execute(get);
			BufferedReader br = new BufferedReader(new InputStreamReader(resp
					.getEntity().getContent()));
			String str = null;
			StringBuilder sb = new StringBuilder();

			while ((str = br.readLine()) != null) {
				sb.append(str).append("\n");
			}
			br.close();
			String rotation = sb.toString();
	        StringTokenizer st = new StringTokenizer(rotation, ";");
	        for(int i = 0; i < 10; i++){
	        	rota_index[i] = Integer.parseInt(st.nextToken());
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	public void process(String url){
		try {
			int rote_index = 0;
			Source source = new Source(new URL(url));
			List<Element> sss = source.getAllElements(HTMLElementName.DIV);
			for(int i = 0; i < sss.size(); i++){
		    	String ss = sss.get(i).getAttributeValue("class");
		    	if(ss == null){
		    		continue;
		    	}
		    	if(ss.equals("mian_champion")){
		    		rote_index = i;
		    		break;
		    	}
			}
	    	Element atags = source.getAllElements(HTMLElementName.DIV).get(rote_index);
	    	int champ_index = 0;
			for(int i = 0; i < atags.getAllElements().size(); i++){
		    	if(atags.getAllElements().get(i).getAttributeValue("href") != null){
					if(atags.getAllElements().get(i).getAttributeValue("href").length() < 38){
						continue;
					}

					if(atags.getAllElements().get(i).getAttributeValue("href").substring(0, 37).equals("./GameInfo/info_champion_sub.php?idx=")){
						 rota_index[champ_index] = Integer.parseInt(atags.getAllElements().get(i).getAttributeValue("href").substring(37, atags.getAllElements().get(i).getAttributeValue("href").length()));
						 champ_index++;
					}
		    	}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(Lolkor.this)
			.setTitle("LOL백과사전")
			.setMessage("종료 하시겠습니까?")
			.setIcon(R.drawable.icon)
			.setPositiveButton("예", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					android.os.Process.killProcess(android.os.Process.myPid()); 
					
				}
				
			})
			.setNegativeButton("아니오", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
				
			})
			.show();
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, ++volume, AudioManager.FLAG_SHOW_UI);	
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, --volume, AudioManager.FLAG_SHOW_UI);
		}else if(keyCode == KeyEvent.KEYCODE_MENU){
			return false;
		}
		return true;
	}
    
	public String loadUpdate() throws IOException {
		AssetManager assetManager = this.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream)assetManager.open("update.txt"); 
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        String line;
        StringBuilder data = new StringBuilder();
        while((line=br.readLine()) != null){
        	data.append(line);
        	data.append("\r\n");
        }
        return data.toString();
	}
	
    @Override
    public void onClick(View v) {
    	Intent intent;
    	switch(v.getId()){
    	case R.id.champion_info:
    		intent = new Intent(this, ChampionList.class);
    		this.startActivity(intent);
    		break;
    	case R.id.item_info:
    		intent = new Intent(this, ItemMenu.class);
    		this.startActivity(intent);
    		break;
    	case R.id.mastery_info:
    		intent = new Intent(this, Masteries.class);
    		this.startActivity(intent);
    		break;
    	case R.id.spells_info:
    		intent = new Intent(this, SummonerSpells.class);
    		this.startActivity(intent);
    		break;
    	case R.id.server_status:
    		
    		new AlertDialog.Builder(this)
			.setIcon(R.drawable.icon)
			.setTitle("LOL백과사전")
			.setMessage("메뉴를 선택하세요.")
			.setPositiveButton("랭킹정보", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
		    		Intent intent = new Intent(Lolkor.this, RankingBoard.class);
					Lolkor.this.startActivity(intent); 
				}
			})
			.setNeutralButton("전적정보", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent intent = new Intent(Lolkor.this, ServerStatus.class);
					Lolkor.this.startActivity(intent);    
				}
			})
			.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
			.create().show();   
    	
			//intent = new Intent(Lolkor.this, ServerStatus.class);
			//Lolkor.this.startActivity(intent);    
    		break;
    	case R.id.builder:
    		intent = new Intent(Lolkor.this, Builder.class);
			Lolkor.this.startActivity(intent);       
    		break;
    	case R.id.jugle_timer:
    		intent = new Intent(Lolkor.this, JungleTimer.class);
			Lolkor.this.startActivity(intent);       
    		break;
    	case R.id.option:
    		intent = new Intent(Lolkor.this, Option.class);
			Lolkor.this.startActivity(intent); 
    		break;
    	case R.id.abbreviation:
    		intent = new Intent(Lolkor.this, Abbreviation.class);
			Lolkor.this.startActivity(intent); 
    		break;
    	case R.id.sale_info:
    		sale_skin.clear();
    		sale_champ.clear();
			if (pd == null) {
				pd = ProgressDialog.show(Lolkor.this, "", "세일정보를 받아오고 있습니다.", true);
				pd.show();
			}
    		Thread t = new Thread(mSaleUpdate);
    		t.start();
    		break;
    	}
    }
    
	final Runnable mSaleUpdate = new Runnable() {
		public void run() {
			if(Utils.isNetwork(Lolkor.this)){	
				process2("http://lol.inven.co.kr/");
	            new Thread(new Runnable() {
	                @Override
	                public void run() {    
	                    runOnUiThread(new Runnable(){
	                        @Override
	                         public void run() {
	                			if (pd != null) {
	                				pd.dismiss();
	                				pd = null;
	                			}
	                    		HistoryDialog hd = new HistoryDialog(Lolkor.this, skindateTitle.substring(5, skindateTitle.length()), sale_skin, sale_champ, skindateText);
	                    		hd.show();
	                         }
	                    });
	                }
	            }).start(); 
			}else{
				Utils.showDialog(Lolkor.this, "알림", "네트워크 오류.");
			}
		}
	};
    String skindateUrl;
    String skindateTitle;
    String skindateText;
	public void process2(String url){
		try {
		  	Source source = new Source(new URL(url));
	    	source.fullSequentialParse();
	    	String txt = null;
	    	Element e2 = null;
	    	Element e3 = null;
	    	List<Element> atags = source.getAllElements(HTMLElementName.DIV);
	    	int divNum = 0;
	    	for(int i = 0; i < atags.size(); i++){
	    		Element e = atags.get(i);
	    		if(e.getTextExtractor().toString().length() >= 9 && 
	    				e.getTextExtractor().toString().substring(0, 9).equals("이주의 세일 품목")){
	    			divNum = i;
	    			break;
	    		}
	    	}
	    	Element e = atags.get(divNum);
	    	atags = e.getAllElements(HTMLElementName.SPAN);
	    	String[] sale_url = new String[atags.size()/2];
	    	for(int i = 0; i < atags.size()/2; i++){
	    		e2 = (Element) atags.get(i*2);
	    		txt = e2.getContent().toString();
	    		if(e2.getAllElements(HTMLElementName.A).size() > 0){
	        		e3 = e2.getAllElements(HTMLElementName.A).get(0);
	        		sale_url[i] = e3.getAttributeValue("href");
	        	//	Log.i("spen"+atags.size(), e3.getAttributeValue("href"));	
	    		}
	    	}
	    	skindateUrl = e.getAllElements(HTMLElementName.DT).get(0).getAllElements(HTMLElementName.A).get(0).getAttributeValue("href");
	    	if(!skindateUrl.substring(0, 41).equals("http://www.inven.co.kr/board/powerbbs.php")){
		    	skindateUrl = e.getAllElements(HTMLElementName.SPAN).get(0).getAllElements(HTMLElementName.A).get(0).getAttributeValue("href");
	    	}
	    	atags = e.getAllElements(HTMLElementName.A);
	    	SaleInfo info = null;
	    	boolean skinSale = true;
	    	for(int i = 0; i < atags.size(); i++){
	    		e2 = (Element) atags.get(i);
	    		txt = e2.getContent().toString();
	    		if(e2.getAllElements(HTMLElementName.IMG).size() <= 0){
	    			if(txt.length() > 8){
	    				if(txt.equals("챔피언 50% Sale")){
	        				skinSale = false;	
	    				}else if(txt.indexOf("챔피언") != -1){
	         				skinSale = false;	
	    				}
	    				continue;
	    			}
	    			if(txt.trim().equals("")){
		        		info.price = 0;
	    			}else{
		        		info.price = Integer.parseInt(txt);	
	    			}
	        		info.url = sale_url[i/2-1];
	        	//	Log.i("price"+i, txt);
	        		if(skinSale){
	        			sale_skin.add(info);
	        		}else{
	        			sale_champ.add(info);
	        		}
	    		}else{
	        		info = new SaleInfo();
	        		e3 = e2.getAllElements(HTMLElementName.IMG).get(0);
	        		info.img = e3.getAttributeValue("src");
	    		}
	    	}
		  	source = new Source(new URL(skindateUrl));
	    	source.fullSequentialParse();
	    	txt = null;
    		Log.i("skindateUrl", skindateUrl);
    		try{
    	    	skindateTitle = source.getAllElements(HTMLElementName.DIV).get(7).getAllElements(HTMLElementName.H2).get(0).getTextExtractor().toString();
    	    	skindateText = source.getAllElements(HTMLElementName.DIV).get(11).getContent().toString();	
    	    	int end = skindateText.indexOf("상품명");
    	    	skindateText = skindateText.substring(0, end);
    		}catch(Exception e4){
    			skindateTitle = "[세 일]오늘의 세일";
    			skindateText = "냉무";
    		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	class SaleInfo{
		String url;
		int price;
		String img;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 0, 0, "카드 게임");   
		menu.add(Menu.NONE, 1, 1, "20초 퀴즈 게임");   
		menu.add(Menu.NONE, 2, 2, "카드 랭킹보기");  
		menu.add(Menu.NONE, 3, 3, "퀴즈 랭킹보기");  
		boolean result = super.onCreateOptionsMenu(menu);
		return result;   
	} 
	
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch(item.getItemId()){ 
		case 0:
			intent = new Intent(this, CardTurn.class);
			this.startActivity(intent);
			break;
		case 1:
			if(Quiz.N_QUIZ_INDEX.size() <= 0){
	  	    	int n_quiz_size = 0;
	    		try {
		    		AssetManager assetManager = getResources().getAssets();
		    		AssetInputStream ais;
	    			ais = (AssetInputStream)assetManager.open("quiz.txt");
	    	        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
	    	        String line;
	    	        while((line=br.readLine()) != null){
	    	        	n_quiz_size++;
	    	        }
	    		} catch (IOException e) {
	    		} 
				for(int i = 0; i < n_quiz_size; i++){
					Quiz.N_QUIZ_INDEX.add(i);
				}
			}
			Collections.shuffle(Quiz.N_QUIZ_INDEX);
			intent = new Intent(this, Quiz.class);
			intent.putExtra("stage", 1);
			this.startActivity(intent);
			break;
		case 2:
			StringBuilder sb = new StringBuilder();
			try {
				HttpClient client = new DefaultHttpClient();
				HttpPost get = new HttpPost();
				get.setURI(new URI("http://ghdnjs9012.com/CardRanking.php"));

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("uuid", Utils.GetDevicesUUID(this)));
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
				get.setEntity(entity);

				HttpResponse resp = client.execute(get);
				BufferedReader br = new BufferedReader(new InputStreamReader(resp
						.getEntity().getContent()));
				String str = null;

				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			new AlertDialog.Builder(this)
			.setMessage(Html.fromHtml(sb.toString()))
			.setPositiveButton("닫기", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
			.create().show();	
			break;
		case 3:
			sb = new StringBuilder();
			try {
				HttpClient client = new DefaultHttpClient();
				HttpPost get = new HttpPost();
				get.setURI(new URI("http://ghdnjs9012.com/QuizRanking.php"));

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("uuid", Utils.GetDevicesUUID(this)));
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
				get.setEntity(entity);

				HttpResponse resp = client.execute(get);
				BufferedReader br = new BufferedReader(new InputStreamReader(resp
						.getEntity().getContent()));
				String str = null;

				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			new AlertDialog.Builder(this)
			.setMessage(Html.fromHtml(sb.toString()))
			.setPositiveButton("닫기", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
			.create().show();	
			break;
		}
		return ( super.onOptionsItemSelected(item)); 
	}
}